// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'boyi-5g77xpkp0aa0181c'
})

// 云函数入口函数
exports.main = async (event, context) => {

  /** 检查是否正确获取用户的openId start */
  const wxContext = cloud.getWXContext();
  console.log(wxContext);
  if(wxContext.OPENID == undefined) {
    var result = {};
    result.errCode = 1;
    result.errMsg = "未能正确返回openId";
    var data = {};
    result.data = data;
    return result;
  }
  /** 检查是否正确获取用户openId end */
  
  // 实例化数据库
  const db = cloud.database();
  console.log(db);

  /** 根据openId查询用户表 start */
  var user;
  await db.collection('userInfo')
  .where({
    openId: wxContext.OPENID
  })
  .get()
  .then(res => {
    console.log(res.data);
    user = res.data[0];  
  });
  /** 根据openId查询用户表 end */

  // 如果没有查询到
  if(user == undefined) {
    var result = {};
    result.errCode = 0;
    result.errMsg = "该用户未绑定";
    var data = {};
    data.openId = wxContext.OPENID;
    data.exist = false;
    result.data = data;
    return result;
  }

  // 如果查询到了
  var result = {};
  result.errCode = 0;
  result.errMsg = "该用户已经绑定";
  var data = {};
  data.openId = wxContext.OPENID;
  data.exist = true;
  var household = {};
  household.name = user.name;
  household.phone = user.phone;
  household.building = user.building;
  household.room = user.room;
  data.household = household;
  result.data = data;
  return result;
}